/**
 * 
 */
package com.dummies.android.taskreminder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * @author vanch_000
 * 
 */
public class ReminderEditActivity extends Activity implements OnClickListener {

	private EditText mTitleText;
	private Button mConfirmButton;
	private Button mDateButton;
	private Button mTimeButton;
	private TextView lblDate;
	private TextView lblTime;
	private EditText mBodyText;

	private static final int DATE_PICKER_DIALOG = 0;
	private static final int TIME_PICKER_DIALOG = 1;
	private static final String DATE_FORMAT = "yyyy-MM-dd";
	private static final String TIME_FORMAT = "kk:mm";
	public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";

	RemindersDbAdapter mDbHelper;
	private Calendar mCalendar;
	private Long mRowId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// init db connect
		mDbHelper = new RemindersDbAdapter(this);
		mDbHelper.open();
		// set layout
		setContentView(R.layout.reminder_edit);
		// find view
		mConfirmButton = (Button) findViewById(R.id.confirm);
		mDateButton = (Button) findViewById(R.id.remider_date);
		mTimeButton = (Button) findViewById(R.id.remider_time);
		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		lblDate = (TextView) findViewById(R.id.lblDate);
		lblTime = (TextView) findViewById(R.id.lblTime);

		// regeister event listener
		mCalendar = Calendar.getInstance();
		mConfirmButton.setOnClickListener(this);
		registerButtonListenersAndSetDefaultText();

		Intent intent = getIntent();
		if (intent != null && intent.getExtras() != null) {
			mRowId = intent.getExtras().getLong(RemindersDbAdapter.KEY_ROWID);
		}
		if (mRowId != null && mRowId > 0) {
			Cursor cursor = mDbHelper.fetchReminder(mRowId);
			if (cursor != null) {
				cursor.moveToFirst();
				int dateTimeColumnIndex = cursor
						.getColumnIndex(RemindersDbAdapter.KEY_DATE_TIME);
				int titleColumnIndex = cursor
						.getColumnIndex(RemindersDbAdapter.KEY_TITLE);
				int bodyColumnIndex = cursor
						.getColumnIndex(RemindersDbAdapter.KEY_BODY);
				if (cursor.isFirst()) {
					String dateTime = cursor.getString(dateTimeColumnIndex);
					String title = cursor.getString(titleColumnIndex);
					String body = cursor.getString(bodyColumnIndex);
					mTitleText.setText(title);
					mBodyText.setText(body);
					SimpleDateFormat format = new SimpleDateFormat(
							ReminderEditActivity.DATE_TIME_FORMAT);
					java.util.Date cal;
					try {
						cal = format.parse(dateTime);
						mCalendar.setTime(cal);
					} catch (ParseException e) {
						Log.d("==ERROR partTime edit activity==", "" + e);
						e.printStackTrace();
					}
				}
			}
			cursor.close();
		}

		// get param
		/*
		 * if (getIntent() != null) { Bundle extras = getIntent().getExtras();
		 * int rowId = extras != null ? extras.getInt("RowId") : -1; }
		 * 
		 * Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain");
		 * i.putExtra(Intent.EXTRA_TEXT, "Hey Everybody");
		 * i.putExtra(Intent.EXTRA_SUBJECT, "My subject"); Intent chooser =
		 * Intent.createChooser(i, "Who should handle this?");
		 * startActivity(chooser);
		 */
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			AlertDialog.Builder build = new AlertDialog.Builder(
					ReminderEditActivity.this);
			build.setMessage("Are you sure you want to save the task?")
					.setTitle("Are you sure")
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// save
									saveState();
									setResult(RESULT_OK);
									Toast.makeText(
											ReminderEditActivity.this,
											getString(R.string.task_saved_message),
											Toast.LENGTH_SHORT).show();
									finish();
								}
							})
					.setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			build.create().show();

			break;

		default:
			break;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private void saveState() {
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
		String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());

		if (title == null || title.trim() == "") {
			Toast.makeText(ReminderEditActivity.this,
					"Title must be filled in", Toast.LENGTH_SHORT).show();
		}
		if (mRowId == null) {
			long id = mDbHelper.createReminder(title, body, reminderDateTime);
			if (id > 0) {
				mRowId = id;
				new ReminderManager(this).setReminder(mRowId, mCalendar,
						title, body);
			}
		} else {
			if (mDbHelper.updateReminder(mRowId, title, body, reminderDateTime)) {
				Log.d("==updateReminder==", "true");
				new ReminderManager(this).setReminder(mRowId, mCalendar,
						title, body);
			}
		}
	}

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_PICKER_DIALOG:
			return showDatePicker();
		case TIME_PICKER_DIALOG:
			return showTimePicker();
		}
		return super.onCreateDialog(id);
	}

	private Dialog showTimePicker() {
		TimePickerDialog timePicker = new TimePickerDialog(
				ReminderEditActivity.this, new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
						mCalendar.set(Calendar.MINUTE, minute);
					}
				}, mCalendar.get(Calendar.HOUR_OF_DAY),
				mCalendar.get(Calendar.MINUTE), true);

		return timePicker;
	}

	private Dialog showDatePicker() {
		DatePickerDialog datePicker = new DatePickerDialog(
				ReminderEditActivity.this, new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						mCalendar.set(Calendar.YEAR, year);
						mCalendar.set(Calendar.MONTH, monthOfYear);
						mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
						updateDateButtonText();
					}
				}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH),
				mCalendar.get(Calendar.DAY_OF_MONTH));
		return datePicker;
	}

	private void registerButtonListenersAndSetDefaultText() {
		mDateButton.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_PICKER_DIALOG);
				updateDateButtonText();
			}
		});

		mTimeButton.setOnClickListener(new OnClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(TIME_PICKER_DIALOG);
				updateTimeButtonText();
			}
		});

		updateDateButtonText();
		updateTimeButtonText();
	}

	@SuppressLint("SimpleDateFormat")
	private void updateTimeButtonText() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);
		String dateForButton = dateFormat.format(mCalendar.getTime());
		lblTime.setText(dateForButton);
	}

	@SuppressLint("SimpleDateFormat")
	private void updateDateButtonText() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
		String dateForButton = dateFormat.format(mCalendar.getTime());
		lblDate.setText(dateForButton);
	}
	
	/**
	 * Sets DateDue field to the next repeat cycle, you still need to call setAlarm()
	 * @param context
	 * @param id
	 *//*
	public Task setRepeatingAlarm(Context context, int id){
		TasksDataSource db = TasksDataSource.getInstance(context);
		Task task = db.getTask(id);    	
		Calendar newDateDue = (Calendar) task.getDateDueCal().clone();
		int repeatType;
		
		switch(task.getRepeatType()){
		case TaskConstant.MINUTES:
			repeatType = Calendar.MINUTE;
			break;
		case TaskConstant.HOURS:
			repeatType = Calendar.HOUR_OF_DAY;
			break;
		case TaskConstant.DAYS:
			repeatType = Calendar.DAY_OF_YEAR;
			break;
		case TaskConstant.WEEKS:
			repeatType = Calendar.WEEK_OF_YEAR;
			break;
		case TaskConstant.MONTHS:
			repeatType = Calendar.MONTH;
			break;
		case TaskConstant.YEARS:
			repeatType = Calendar.YEAR;
			break;
		default:
			repeatType = Calendar.DAY_OF_YEAR;
			break;
		}
		
		// Due date is behind current time, task was finished late
		if (newDateDue.getTimeInMillis() <= System.currentTimeMillis()) {
			while(newDateDue.getTimeInMillis() <= System.currentTimeMillis()){
				newDateDue.add(repeatType, task.getRepeatInterval());
			}
		} else {
			// Due date is ahead of current time, task was finished early
			newDateDue.add(repeatType, task.getRepeatInterval());
			
			AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, newDateDue.getTimeInMillis(), 
					getPendingIntent(context, task.getID()));
			
			// Return task unchanged, it will uncomplete automatically when
			// TaskAlarmService when current time >= date due
			return task;
		}
		
		task.setDateDue(newDateDue.getTimeInMillis());
		task.setDateModified(System.currentTimeMillis());
		task.setIsCompleted(false);
		db.updateTask(task);

		return task;
	}*/

}
